import React from 'react'
import { NavLink } from 'react-router-dom'
import { connect } from 'react-redux'
import BattleItem from './BattleItem.tsx'
import RoundReplay from './RoundReplay.tsx'
import './battleDetail.less'

const mapStateToProps = (state) => {
  return {
    userInfo: state.app.userInfo
  }
}
class BattleDetailBase extends React.Component<any, any> {
  public constructor(props) {
    super(props)
    this.state = {
      period: 1,
      gameId: 1,
      gameName: '',
      combatList: [],
      loading: false,
      isShowQrcode: false,
      qrcodeUrl: '',
      qrcodeNickname: '',
      lftid: 0
    }
  }

  public componentDidMount() {
    console.log(this.props.match.params.gameName)
    const { gameId, gameName } = this.props.match.params
    this.setState({ gameId, gameName })
    const ing = document.querySelectorAll('.ingredient')
    _.toArray(ing).forEach(element => {
      element.style.height = Math.round(element.offsetWidth / (2.852  *  3)) + 'px'
    })
    this.queryBattles(this.state.period)
  }

  activePeroid(period) {
    console.log('peroid', period);
    if (this.state.period === period) {
      return
    }
    this.setState({ period })
    this.queryBattles(period)
  }

  queryBattles(period) {
    const { gameId, gameName } = this.props.match.params
    // recordType:查询什么时间段的数据（1代表今天，2代表一周，3代表进3个月，4代表近3天，5代表所有）
    const query = {
      gameId: gameId,
      recordType: period,
      pageNo: 0,
      limit: 50
    }
    const url = `${config.pre}/recordCenter/${gameId}/${query.recordType}/${query.pageNo}/${query.limit}`
    const opt = { method: 'GET' }
    this.setState({ loading: true })
    fetchJson(url, opt).then(data => {
      this.setState({ loading: false })
      console.error(data)
      if (data.result) {
        this.setState({ combatList: [] })
        return
      }
      const { combatList, roombatList } = data.data.dataList[0]
      const zipResult = _.zipWith(combatList, roombatList, (c, r) => ({ ...c, ...r }))
      console.error('zipResult', zipResult)

      zipResult.forEach(rule => {
        switch (rule.gameType) {
          case "BULLFIGHT":
            rule._appendInfo = util.gameUtil.classicBullRules(JSON.parse(rule.roomDescribe))
            break
          case "OXFIGHT":
            rule._appendInfo = util.gameUtil.fightBullRules(JSON.parse(rule.roomDescribe))
            break
          case "HONGZHONG":
            rule._appendInfo = util.gameUtil.majiangRules(JSON.parse(rule.roomDescribe))
            break
          case "DIANZINIU":
            rule._appendInfo = util.gameUtil.dianziBullRules(JSON.parse(rule.roomDescribe))
            break
          case "JINHUA":
            rule._appendInfo = util.gameUtil.jinhuaRules(JSON.parse(rule.roomDescribe))
            break
          case "SANGONG":
            rule._appendInfo = util.gameUtil.sangongRules(JSON.parse(rule.roomDescribe))
            break
          case "HUACHUAN":
            rule._appendInfo = util.gameUtil.pjchuanRules(JSON.parse(rule.roomDescribe))
            break
          case "RUNFAST":
            rule._appendInfo = util.gameUtil.runRules(JSON.parse(rule.roomDescribe), rule.totalTurns)
            break
          case "PJMAHJONG":
            rule._appendInfo = util.gameUtil.znRules(JSON.parse(rule.roomDescribe))
            break
          default:
            rule._appendInfo = { ruleName: '' }
            break
        }
      })
      this.setState({ combatList: zipResult })
    })
  }

  closeQrcode() {
    this.setState({
      isShowQrcode: false
    })
  }

  showQrcodeItem(value) {
    let body = {
      uid: value.uid
    };
    console.log(value, 'value')
    var token = Cookies.get('token')
    var areaCode = Cookies.get('areaCode')
    var url = `${config.pre}/personalCenter/payQr/show`;
    var opt = {
      method: 'POST',
      headers: { Authorization: token, AreaCode: areaCode, 'Content-Type': 'application/json;charset=utf-8' },
      body: JSON.stringify(body)
    };
    fetch(url, opt).then(res => res.json()).then(data => {
      console.log('data', data)
      if (data.result === 0) {
        let url = data.data;
        if (window.location.href.match('10.10.10')) {
          url = url.replace('http://127.0.0.1:8080', 'https://lefantian.jiahuagame.com');
        }
        this.setState({
          qrcodeUrl: url,
          isShowQrcode: true,
          qrcodeNickname: value.nickName
        });
      } else {
        alert(value.nickName + '没有上传收款码.');
      }
    })
  }

  public render() {
    const { inviteId, tip, period, combatList, loading, showRoundRelplay, gameName, isShowQrcode, qrcodeUrl, lftid  } = this.state
    const { userInfo } = this.props
    console.error(combatList)
    return <div className="view-page battle-view">
      <div className="detail-top text-center pure-g">
        <img src="img/battle/detail-top.png" className="full detail-top-bg" alt="" />
        <div className="pure-u-1-2">
          <img src={userInfo.headUrl} className="detail-top-header" alt="" />
          {userInfo.nickname}
        </div>
        {/* <div className="pure-u-1-2">总局数: 312</div> */}
        {/* <div className="pure-u-1-3"></div>         */}
      </div>
      <div className="detail-middle">
        <div className="content">
          <div className="header pure-g">
            <div className="pure-u-1-1" >
              <div className="ingredient left-radius">
                {
                  period === 1 ? <img src="img/battle/1-default-2.png" className="label" alt="" /> :
                    <img src="img/battle/1-default-2.png" className="label" alt="" />
                }
              </div>
            </div>
            {/*<div className="pure-u-1-3" onClick={this.activePeroid.bind(this, 2)}>
              <div className="ingredient">
                {
                  period === 2 ? <img src="img/battle/7-active.png" className="label" alt="" /> :
                    <img src="img/battle/7-default.png" className="label" alt="" />
                }
              </div>
            </div>*/}
         {/*   <div className="pure-u-1-3" onClick={this.activePeroid.bind(this, 5)}>
              <div className="ingredient right-radius">
                {
                  period === 5 ? <img src="img/battle/all-active.png" className="label" alt="" /> :
                    <img src="img/battle/all-default.png" className="label" alt="" />
                }
              </div>
            </div>*/}
          </div>
          <div className="info">
            {
              combatList.map((battle, index) => (<BattleItem showQrcode={this.showQrcodeItem.bind(this)} data={battle} key={index}></BattleItem>))
            }
            {
              combatList.length === 0 && !loading ? <div className="empty-tip">暂无记录</div> : null
            }
          </div>
        </div>
      </div>
      <div className="usercenter-bottom">
        <img className="bar-half" src="img/userCenter/records-bottom.png" alt=""/>
        <img className="user-bottom-bg" src="img/userCenter/user-bottom-bg.png" alt=""/>
        <NavLink to="/Records"><img className="back" src="img/userCenter/user-back.png" alt="" /></NavLink>
      </div>
      {
        isShowQrcode ? <div className="app-qrcode-dialog-wrapper">
          <div className="qrcode-dialog">
            <div className="description">{this.state.qrcodeNickname}的收款二维码</div>
            <img onClick={this.closeQrcode.bind(this)} className="qrcode-close" src="img/createGame/close-btn.png" alt="" />
            <div className="upload-qrcode">
              <img src={qrcodeUrl} alt="" />
            </div>
            <div className="upload-actions">
            </div>
          </div>
        </div> : null
      }

    </div>
  }

}

export default connect(mapStateToProps)(BattleDetailBase)